package com.baidu.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baidu.pojo.Permission;
import com.baidu.pojo.Role;
import com.baidu.pojo.User;
import com.baidu.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

	@Reference
	private UserService userService;

	/**
	 * 根据用户名查询用户信息
	 * @param s
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//		远程调用用户服务，根据用户名查询用户信息
		 User user= userService.findByUsername(s);
		 if (user==null){
		 	return null;
		 }

		ArrayList<GrantedAuthority> list = new ArrayList<>();
		Set<Role> roles = user.getRoles();
		if (roles!=null){//授权角色
			for (Role role : roles) {//遍历该用户的角色及角色对应的权限，把这写角色及权限添加到一个集合，注入给security.
				list.add(new SimpleGrantedAuthority(role.getKeyword()));

//				授权权限
				Set<Permission> permissions = role.getPermissions();
				if (permissions!=null){
					for (Permission permission : permissions) {
						list.add(new SimpleGrantedAuthority(permission.getKeyword()));

					}
				}

			}

		}
		org.springframework.security.core.userdetails.User userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);

		return userDetails;
	}
}
